<template>
  <view class="line-detail-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-left">
        <uni-icons type="left" size="20" color="#333" @click="goBack"></uni-icons>
        <text class="page-title">{{ transferCode }}</text>
      </view>
    </view>

    <!-- 调拨明细 -->
    <view class="line-overview" v-if="lineInfo">
      <view class="overview-header">
        <view class="header-left">
          <text class="overview-title">调拨明细</text>
          <view class="line-status" :class="getLineStatusClass()">
            {{ getLineStatusText() }}
          </view>
        </view>
      </view>
      
      <view class="overview-content">
        <view class="content-grid">
          <view class="grid-item">
            <text class="item-label">物料名称</text>
            <text class="item-value">{{ lineInfo.itemName }}</text>
          </view>
          <view class="grid-item">
            <text class="item-label">物料编码</text>
            <text class="item-value">{{ lineInfo.itemCode }}</text>
          </view>
          <view class="grid-item">
            <text class="item-label">规格型号</text>
            <text class="item-value">{{ lineInfo.specification }}</text>
          </view>
            <view class="grid-item">
              <text class="item-label">转移数量</text>
              <text class="item-value">{{ lineInfo.quantityTransfer }} {{ lineInfo.unitName || '' }}</text>
            </view>
          <view class="grid-item" v-if="lineInfo.batchCode">
            <text class="item-label">批次号</text>
            <text class="item-value">{{ lineInfo.batchCode }}</text>
          </view>
          <view class="grid-item">
            <text class="item-label">调出仓库</text>
            <text class="item-value">{{ lineInfo.outWarehouseName || '-' }}</text>
          </view>
          <view class="grid-item">
            <text class="item-label">调入仓库</text>
            <text class="item-value">{{ lineInfo.inWarehouseName || '-' }}</text>
          </view>
          <view class="grid-item progress-item">
            <text class="item-label">上架进度</text>
            <view class="progress-info">
              <text class="progress-text">已上架 {{ getReceivedCount() }}/{{ getSentCount() }} {{ lineInfo.unitName || '' }}</text>
              <view class="progress-bar">
                <view 
                  class="progress-fill" 
                  :style="{ width: getProgressWidth() + '%' }"
                ></view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 明细列表 -->
    <view class="details-section" v-if="transferDetails.length > 0">
      <view class="section-header">
        <text class="section-title">明细列表</text>
        <text class="section-count">共 {{ transferDetails.length }} 条</text>
      </view>
      
      <view class="details-list">
        <view 
          class="detail-item" 
          v-for="(detail, index) in transferDetails" 
          :key="detail.detailId"
        >
          <view class="item-header">
            <view class="item-title">
              <text class="item-number">#{{ index + 1 }}</text>
              <text class="item-identifier">{{ getItemIdentifier(detail) }}</text>
            </view>
            <view class="item-status" :class="getItemStatusClass(detail.itemStatus)">
              {{ getItemStatusText(detail.itemStatus) }}
            </view>
          </view>
          
          <view class="item-info-grid">
            <view class="info-row">
              <text class="info-label">数量</text>
              <text class="info-value">{{ detail.quantity }} {{ detail.unitName || '' }}</text>
            </view>
            <view class="info-row" v-if="detail.batchCode">
              <text class="info-label">批次号</text>
              <text class="info-value">{{ detail.batchCode }}</text>
            </view>
            <view class="info-row" v-if="detail.sn">
              <text class="info-label">SN</text>
              <text class="info-value">{{ detail.sn }}</text>
            </view>
          </view>
          
          <!-- 发货信息 -->
          <view class="shipment-info" v-if="detail.itemStatus >= 1">
            <view class="info-section-title">
              <uni-icons type="paperplane" size="14" color="#007AFF"></uni-icons>
              <text>发货信息</text>
            </view>
            <view class="info-grid">
              <view class="info-item" v-if="detail.outWarehouseName">
                <text class="info-label">发货仓库</text>
                <text class="info-value">{{ detail.outWarehouseName }}</text>
              </view>
              <view class="info-item" v-if="detail.outLocationName">
                <text class="info-label">发货库区</text>
                <text class="info-value">{{ detail.outLocationName }}</text>
              </view>
              <view class="info-item" v-if="detail.outAreaCode">
                <text class="info-label">发货库位</text>
                <text class="info-value">{{ detail.outAreaCode }}</text>
              </view>
              <view class="info-item" v-if="detail.shipConfirmUserName">
                <text class="info-label">发货人</text>
                <text class="info-value">{{ detail.shipConfirmUserName }}</text>
              </view>
              <view class="info-item" v-if="detail.shipTime">
                <text class="info-label">发货时间</text>
                <text class="info-value">{{ formatTime(detail.shipTime) }}</text>
              </view>
            </view>
          </view>
          
          <!-- 上架信息 -->
          <view class="receive-info" v-if="detail.itemStatus === 2">
            <view class="info-section-title">
              <uni-icons type="checkmarkempty" size="14" color="#28a745"></uni-icons>
              <text>上架信息</text>
            </view>
            <view class="info-grid">
              <view class="info-item" v-if="detail.inWarehouseName">
                <text class="info-label">上架仓库</text>
                <text class="info-value">{{ detail.inWarehouseName }}</text>
              </view>
              <view class="info-item" v-if="detail.inLocationName">
                <text class="info-label">上架库区</text>
                <text class="info-value">{{ detail.inLocationName }}</text>
              </view>
              <view class="info-item" v-if="detail.inAreaCode">
                <text class="info-label">上架库位</text>
                <text class="info-value">{{ detail.inAreaCode }}</text>
              </view>
              <view class="info-item" v-if="detail.receiveConfirmUserName">
                <text class="info-label">上架人</text>
                <text class="info-value">{{ detail.receiveConfirmUserName }}</text>
              </view>
              <view class="info-item" v-if="detail.receiveTime">
                <text class="info-label">上架时间</text>
                <text class="info-value">{{ formatTime(detail.receiveTime) }}</text>
              </view>
            </view>
          </view>
          
          <!-- 上架按钮：对已发货/已上架状态显示，且调拨单状态为待上架时才能操作（可以重复上架） -->
          <view class="item-actions" v-if="detail.itemStatus >= 1 && canShelf">
            <button 
              class="action-btn receive-btn" 
              @click.stop="receiveSingleItem(detail)"
            >
              <uni-icons type="checkmarkempty" size="14" color="#fff"></uni-icons>
              上架
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="transferDetails.length === 0">
      <uni-icons type="inbox" size="60" color="#ccc"></uni-icons>
      <text class="empty-text">暂无明细数据</text>
    </view>

    <!-- 收货确认弹窗 -->
    <receive-confirm-modal
      :visible="showReceiveModal"
      :material-info="currentMaterialInfo"
      :fixed-warehouse-id="lineInfo && lineInfo.inWarehouseId"
      @success="handleReceiveSuccess"
      @close="handleReceiveModalClose"
    />
  </view>
</template>

<script>
import { 
  getDetail,
} from '@/api/wm/transfer.js'
import ReceiveConfirmModal from '@/components/transfer/receive-confirm-modal.vue'

export default {
  name: 'TransferDetailReceive',
  components: {
    ReceiveConfirmModal
  },
  data() {
    return {
      lineId: '',
      transferCode: '',
      transferId: '',
      transferStatus: '', // 调拨单状态
      lineInfo: null,
      transferDetails: [],
      loading: false,
      
      // 收货确认弹窗相关
      showReceiveModal: false,
      currentMaterialInfo: {}
    }
  },
  
  computed: {
    // 是否可以上架（根据调拨单状态判断）
    canShelf() {
      // 只有UN_IN_STOCK（待上架）状态可以上架
      return this.transferStatus === 'UN_IN_STOCK'
    }
  },
  
  onLoad(options) {
    if (options.lineId) {
      this.lineId = options.lineId
    }
    if (options.transferCode) {
      this.transferCode = options.transferCode
    }
    if (options.transferId) {
      this.transferId = options.transferId
    }
    if (options.transferStatus) {
      this.transferStatus = options.transferStatus
    }
    this.loadLineDetails()
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return '-'
      const d = new Date(time)
      const y = d.getFullYear()
      const M = String(d.getMonth() + 1).padStart(2, '0')
      const D = String(d.getDate()).padStart(2, '0')
      const h = String(d.getHours()).padStart(2, '0')
      const m = String(d.getMinutes()).padStart(2, '0')
      const s = String(d.getSeconds()).padStart(2, '0')
      return `${y}-${M}-${D} ${h}:${m}:${s}`
    },
    
    // 加载行明细数据
    loadLineDetails(showLoading = true, showSuccessToast = false) {
      if (!this.lineId) {
        uni.showToast({ title: '数据异常，请刷新后重试', icon: 'none' })
        return
      }
      
      if (showLoading) {
        uni.showLoading({ title: '加载中...' })
      }
      this.loading = true
      
      getDetail(this.lineId).then(response => {
        const data = response.data
        this.lineInfo = data.transferLine || {}
        
        // 对明细列表按itemStatus排序：已拣货待上架(1)排在前面，待发货(0)和已上架(2)排在后面
        const details = data.transferDetails || []
        this.transferDetails = details.sort((a, b) => {
          // 已拣货待上架(1)的排在前面
          if (a.itemStatus === 1 && b.itemStatus !== 1) return -1
          if (a.itemStatus !== 1 && b.itemStatus === 1) return 1
          // 同状态保持原顺序，返回0表示不改变相对位置
          return 0
        })
        
        if (showSuccessToast) {
          uni.showToast({ title: '加载成功', icon: 'success' })
        }
      }).catch(error => {
        console.log('加载明细失败:', error)
        
        if (error === '500') {
          console.log('业务错误，拦截器已显示toast')
        } else {
          uni.showToast({ 
            title: '网络异常，请检查网络连接后重试', 
            icon: 'none',
            duration: 3000
          })
        }
        
        this.lineInfo = null
        this.transferDetails = []
      }).finally(() => {
        if (showLoading) {
          uni.hideLoading()
        }
        this.loading = false
      })
    },
    
    // 收货单个项目
    receiveSingleItem(detail) {
      if (detail.itemStatus < 1) {
        uni.showToast({ title: '只能对已发货的明细进行上架', icon: 'none' })
        return
      }
      
      this.currentMaterialInfo = {
        detailId: detail.detailId,
        itemName: detail.itemName,
        itemCode: detail.itemCode,
        specification: detail.specification,
        quantity: detail.quantity,
        unitName: detail.unitName,
      }
      
      this.showReceiveModal = true
    },
    
    // 处理收货确认弹窗关闭
    handleReceiveModalClose() {
      this.showReceiveModal = false
      this.currentMaterialInfo = {}
    },
    
    // 处理收货成功
    handleReceiveSuccess() {
      this.loadLineDetails(false, false)
    },
    
    // 获取已发出数量
    getSentCount() {
      if (!this.transferDetails || this.transferDetails.length === 0) return 0
      return this.transferDetails
        .filter(detail => detail.itemStatus === 1 || detail.itemStatus === 2)
        .reduce((total, detail) => total + (detail.quantity || 0), 0)
    },
    
    // 获取总数量
    getTotalCount() {
      if (!this.lineInfo || !this.lineInfo.quantityTransfer) return 0
      return this.lineInfo.quantityTransfer
    },
    
    // 获取进度百分比
    getProgressWidth() {
      const sentCount = this.getSentCount()
      if (sentCount === 0) return 0
      const receivedCount = this.getReceivedCount()
      return Math.round((receivedCount / sentCount) * 100)
    },
    
    // 获取已收货数量
    getReceivedCount() {
      if (!this.transferDetails || this.transferDetails.length === 0) return 0
      return this.transferDetails
        .filter(detail => detail.itemStatus === 2)
        .reduce((total, detail) => total + (detail.quantity || 0), 0)
    },
    
    // 获取行状态文本
    getLineStatusText() {
      const sentCount = this.getSentCount()
      const receivedCount = this.getReceivedCount()
      
      if (sentCount === 0) {
        return '待发货'
      }
      
      if (receivedCount === sentCount) {
        return '已上架'
      } else if (receivedCount > 0) {
        return '部分上架'
      } else {
        return '待上架'
      }
    },
    
    // 获取行状态样式
    getLineStatusClass() {
      const sentCount = this.getSentCount()
      const receivedCount = this.getReceivedCount()
      
      if (sentCount === 0) {
        return 'status-waiting'
      }
      
      if (receivedCount === sentCount) {
        return 'status-received'
      } else if (receivedCount > 0) {
        return 'status-partial'
      } else {
        return 'status-pending'
      }
    },
    
    // 获取项目状态文本
    getItemStatusText(itemStatus) {
      const map = {
        0: '待发货',
        1: '待上架',
        2: '已上架'
      }
      return map[itemStatus] || '未知状态'
    },
    
    // 获取项目状态样式
    getItemStatusClass(itemStatus) {
      const map = {
        0: 'status-waiting',
        1: 'status-pending',
        2: 'status-received'
      }
      return map[itemStatus] || 'status-default'
    },
    
    // 获取项目标识符
    getItemIdentifier(detail) {
      if (detail.sn) {
        return detail.sn
      }
      
      if (detail.batchCode) {
        return `批次: ${detail.batchCode}`
      }
      
      return '物料维度'
    }
  }
}
</script>

<style lang="scss" scoped>
.line-detail-container {
  padding: 20rpx;
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 12rpx;
    
    .page-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .transfer-code {
    font-size: 24rpx;
    color: #666;
    background: #f8f9fa;
    padding: 8rpx 12rpx;
    border-radius: 8rpx;
  }
}

.line-overview {
  background: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  
  .overview-header {
    margin-bottom: 16rpx;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16rpx;
      
      .overview-title {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
      }
      
      .line-status {
        padding: 6rpx 12rpx;
        border-radius: 16rpx;
        font-size: 22rpx;
        font-weight: bold;
        
        &.status-pending {
          background: linear-gradient(135deg, #ffeaa7 0%, #fdcb6e 100%);
          color: #d63031;
        }
        
        &.status-partial {
          background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
          color: #fff;
        }
        
        &.status-completed {
          background: linear-gradient(135deg, #55efc4 0%, #00b894 100%);
          color: #fff;
        }
        
        &.status-received {
          background: linear-gradient(135deg, #a29bfe 0%, #6c5ce7 100%);
          color: #fff;
        }
        
        &.status-waiting {
          background: #f8f9fa;
          color: #6c757d;
        }
      }
    }
  }
  
  .overview-content {
    .content-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 16rpx 20rpx;
      
      .grid-item {
        display: flex;
        flex-direction: column;
        
        .item-label {
          font-size: 22rpx;
          color: #666;
          margin-bottom: 6rpx;
        }
        
        .item-value {
          font-size: 24rpx;
          color: #333;
          font-weight: 500;
          word-break: break-all;
        }
        
        &.progress-item {
          grid-column: 1 / -1;
          
          .progress-info {
            display: flex;
            flex-direction: column;
            gap: 8rpx;
            
            .progress-text {
              font-size: 24rpx;
              color: #333;
              font-weight: 500;
            }
            
            .progress-bar {
              height: 8rpx;
              background: #e9ecef;
              border-radius: 4rpx;
              overflow: hidden;
              
              .progress-fill {
                height: 100%;
                background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
                border-radius: 4rpx;
                transition: width 0.3s ease;
              }
            }
          }
        }
      }
    }
  }
}

.details-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;
    
    .section-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
    }
    
    .section-count {
      font-size: 24rpx;
      color: #666;
    }
  }
  
  .details-list {
    .detail-item {
      background: #fff;
      border-radius: 12rpx;
      padding: 20rpx;
      margin-bottom: 16rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.98);
      }
      
      .item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;
        padding-bottom: 12rpx;
        border-bottom: 1rpx solid #f0f0f0;
        
        .item-title {
          display: flex;
          align-items: center;
          gap: 12rpx;
          
          .item-number {
            font-size: 20rpx;
            color: #999;
            background: #f5f5f5;
            padding: 4rpx 8rpx;
            border-radius: 6rpx;
            min-width: 32rpx;
            text-align: center;
          }
          
          .item-identifier {
            font-size: 26rpx;
            font-weight: bold;
            color: #333;
          }
        }
        
        .item-status {
          padding: 6rpx 12rpx;
          border-radius: 12rpx;
          font-size: 22rpx;
          font-weight: bold;
          
          &.status-waiting {
            background: #f5f5f5;
            color: #999;
          }
          
          &.status-pending {
            background: #ffeaa7;
            color: #d63031;
          }
          
          &.status-received {
            background: #55efc4;
            color: #fff;
          }
        }
      }
      
      .item-info-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 12rpx;
        margin-bottom: 16rpx;
        
        .info-row {
          display: flex;
          flex-direction: column;
          
          .info-label {
            font-size: 22rpx;
            color: #666;
            margin-bottom: 4rpx;
          }
          
          .info-value {
            font-size: 24rpx;
            color: #333;
            font-weight: 500;
          }
        }
      }
      
      .shipment-info, .receive-info {
        margin-bottom: 16rpx;
        
        .info-section-title {
          display: flex;
          align-items: center;
          gap: 8rpx;
          margin-bottom: 12rpx;
          font-size: 24rpx;
          font-weight: bold;
          color: #333;
        }
        
        .info-grid {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 12rpx;
          
          .info-item {
            display: flex;
            flex-direction: column;
            
            .info-label {
              font-size: 22rpx;
              color: #666;
              margin-bottom: 4rpx;
            }
            
            .info-value {
              font-size: 24rpx;
              color: #333;
              font-weight: 500;
            }
          }
        }
      }
      
      .receive-info {
        .info-section-title {
          color: #28a745;
        }
      }
      
      .item-actions {
        display: flex;
        gap: 12rpx;
        flex-wrap: wrap;
        margin-top: 16rpx;
        padding-top: 16rpx;
        border-top: 1rpx solid #f0f0f0;
        
        .action-btn {
          display: flex;
          align-items: center;
          gap: 6rpx;
          padding: 10rpx 16rpx;
          border-radius: 8rpx;
          font-size: 22rpx;
          font-weight: bold;
          border: none;
          
          &.receive-btn {
            background: #28a745;
            color: #fff;
          }
          
          &:active {
            transform: translateY(1rpx);
          }
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 40rpx;
  
  .empty-text {
    margin-top: 20rpx;
    font-size: 26rpx;
    color: #999;
  }
}

</style>

